<template>
  <div>
    <div class="gva-search-box">
      <p>节点名称：{{nodeName}}</p>
    </div>
    <div class="gva-table-box">
      <el-table
          :data="hardwareData"
          @sort-change="sortChange"
          @selection-change="handleSelectionChange"
      >

        <el-table-column
            align="left"
            label="型号"
            min-width="150"
            prop="model"
            sortable="custom"
        />
        <el-table-column
            align="left"
            label="类别"
            min-width="150"
            prop="category"
            sortable="custom"
        />
        <el-table-column
            align="left"
            label="安装时间"
            min-width="150"
            prop="install_date"
            sortable="custom"
        />
        <el-table-column
            align="left"
            label="截止保修日期"
            min-width="150"
            prop="warranty_end_date"
            sortable="custom"
        />
        <el-table-column
            align="left"
            label="内网IP地址"
            min-width="150"
            prop="ip_address"
            sortable="custom"
        />
        <el-table-column
            align="left"
            label="CPU型号"
            min-width="150"
            prop="cpu_type"
            sortable="custom"
        />
        <el-table-column
            align="left"
            label="内存"
            min-width="150"
            :formatter="formatMemory"
            prop="member_cache"
            sortable="custom"
        >
          <template #default="scope">
            <el-button
                type="primary"
                link
                @click="openDialogmember(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>

        <el-table-column
            align="left"
            label="磁盘空间"
            :formatter="formatdisk"
            min-width="150"
            prop="disk_space"
            sortable="custom"
        >
          <template #default="scope">
            <el-button
                type="primary"
                link
                @click="openDialogdisk(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
            align="left"
            label="网卡"
            min-width="150"
            prop="network_type"
            sortable="custom"
        />
        <el-table-column
            align="left"
            label="GPU型号"
            min-width="150"
            prop="gpu_type"
            sortable="custom"
        />
      </el-table>
      <div class="gva-pagination">
        <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>

    </div>
    <el-dialog v-model="drawerVisiblemember" width="60%" :before-close="closeDialog" :show-close="false">
      <div style="margin: 20px 10px;">
        <h3>内存信息</h3>
        <div class="info" v-html="detailedMemoryInfo"></div>
      </div>
    </el-dialog>

    <el-dialog v-model="drawerVisibledisk" width="60%" :before-close="closeDialog" :show-close="false">
      <div style="margin: 20px 10px;">
        <h3>磁盘信息</h3>
        <div class="info" v-html="detailedDiskInfo"></div>
      </div>
    </el-dialog>


  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {useRoute} from 'vue-router'
import { ElMessage} from 'element-plus'
import { getNodeHardWare } from '@/api/node'

const route = useRoute()

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const hardwareData = ref([])
const searchInfo = ref({})
const nodeID = ref('')
const nodeName = route.query.NodeName

const detailedMemoryInfo = ref('')
const detailedDiskInfo = ref('')

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const sortChange = ({prop, order}) => {
  if (prop) {
    searchInfo.value.orderKey = prop
    searchInfo.value.desc = order === 'descending'
  }
  getTableData()
}

const handleSelectionChange = (val) => {
  // Handle selection change logic
}

const drawerVisiblemember = ref(false)
const drawerVisibledisk = ref(false)
const form = ref({
  software_id: '',
  updateTime: '',
  program_url: '',
  recordTime: '',
  hardware_id: '',
  category: '',
  main_process_name: '',
  description: ''
})

const openDialogmember = (row) => {
  drawerVisiblemember.value = true
  detailedMemoryInfo.value = formatMemory(row.member_cache)
}

const openDialogdisk = (row) => {
  drawerVisibledisk.value = true
  detailedDiskInfo.value = formatMemory(row.disk_space)
}

const resetForm = () => {
  form.value = {
    software_id: '',
    updateTime: '',
    program_url: '',
    recordTime: '',
    hardware_id: '',
    category: '',
    main_process_name: '',
    description: ''
  }
}

const formatMemory = (memberCache) => {
  try {

    // 如果 memberCache 不是对象，尝试将其解析为 JSON 字符串
    if (typeof memberCache === 'string') {
      const cleanedJson = memberCache.replace(/\n/g, '').replace(/\\/g, '');
      const memory = JSON.parse(cleanedJson);
      console.log('Parsed Memory:', memory);
      return `
    <table style="border-collapse: collapse; width: 100%; border: 1px solid black;text-align: center;">
      <tr>
        <th style="border: 1px solid black; padding: 8px;">品牌</th>
        <th style="border: 1px solid black; padding: 8px;">系列</th>
        <th style="border: 1px solid black; padding: 8px;">单条容量</th>
        <th style="border: 1px solid black; padding: 8px;">总容量</th>
        <th style="border: 1px solid black; padding: 8px;">类型</th>
        <th style="border: 1px solid black; padding: 8px;">模块数</th>
      </tr>
      <tr>
        <td style="border: 1px solid black; padding: 8px;">${memory.brand || '-'}</td>
        <td style="border: 1px solid black; padding: 8px;">${memory.series || '-'}</td>
        <td style="border: 1px solid black; padding: 8px;">${memory.capacity_per_module || '-'}</td>
        <td style="border: 1px solid black; padding: 8px;">${memory.total_capacity || '-'}</td>
        <td style="border: 1px solid black; padding: 8px;">${memory.type || '-'}</td>
        <td style="border: 1px solid black; padding: 8px;">${memory.modules || '-'}</td>
      </tr>
    </table>
      `;
    }
  } catch (e) {
    console.error('内存信息格式化错误:', e);
    return '格式化内存信息失败';
  }
};

const formatdisk = (diskCache) => {
  try {
    // 如果 diskCache 是对象，直接获取 disk_space
    if (typeof diskCache === 'object') {
      const disk = diskCache.disk_space;

      // 如果 disk 也是对象，直接格式化
      if (typeof disk === 'object') {
        console.log('Disk:', disk);
        return `
          <p>品牌: ${disk.brand || '未知'}</p>
          <p>系列: ${disk.series || '未知'}</p>
          <p>单条容量: ${disk.capacity_per_module || '未知'}</p>
          <p>总容量: ${disk.total_capacity || '未知'}</p>
          <p>类型: ${disk.type || '未知'}</p>
          <p>模块数: ${disk.modules || '未知'}</p>
        `;
      }
      // 如果 disk 不是对象，尝试将其解析为 JSON
      else if (typeof disk === 'string') {
        const parsedDisk = JSON.parse(disk);
        console.log('Parsed Disk:', parsedDisk);
        return `
          <p>品牌: ${parsedDisk.brand || '未知'}</p>
          <p>系列: ${parsedDisk.series || '未知'}</p>
          <p>单条容量: ${parsedDisk.capacity_per_module || '未知'}</p>
          <p>总容量: ${parsedDisk.total_capacity || '未知'}</p>
          <p>类型: ${parsedDisk.type || '未知'}</p>
          <p>模块数: ${parsedDisk.modules || '未知'}</p>
        `;
      }
    }

    else if (typeof diskCache === 'string') {
      const cleanedJson = diskCache.replace(/\n/g, '').replace(/\\/g, '');
      const disk = JSON.parse(cleanedJson);
      console.log('Parsed Disk:', disk);
      return `
    <table style="border-collapse: collapse; width: 100%; border: 1px solid black;text-align: center;">
      <tr>
        <th style="border: 1px solid black; padding: 8px;">品牌</th>
        <th style="border: 1px solid black; padding: 8px;">系列</th>
        <th style="border: 1px solid black; padding: 8px;">单条容量</th>
        <th style="border: 1px solid black; padding: 8px;">总容量</th>
        <th style="border: 1px solid black; padding: 8px;">类型</th>
        <th style="border: 1px solid black; padding: 8px;">模块数</th>
      </tr>
      <tr>
        <td style="border: 1px solid black; padding: 8px;">${disk.brand || '-'}</td>
        <td style="border: 1px solid black; padding: 8px;">${disk.series || '-'}</td>
        <td style="border: 1px solid black; padding: 8px;">${disk.capacity_per_module || '-'}</td>
        <td style="border: 1px solid black; padding: 8px;">${disk.total_capacity || '-'}</td>
        <td style="border: 1px solid black; padding: 8px;">${disk.type || '-'}</td>
        <td style="border: 1px solid black; padding: 8px;">${disk.modules || '-'}</td>
      </tr>
    </table>
      `;
    }
  } catch (e) {
    console.error('磁盘信息格式化错误:', e);
    return '格式化磁盘信息失败';
  }
};


const getTableData = async () => {
  try {
    nodeID.value = route.query.nodeId || ''

    if (nodeID.value) {
      const response = await getNodeHardWare(page.value, pageSize.value, nodeID.value) // 使用 node id 调用 API
      if (response.code === 0) {
        hardwareData.value = response.data.HardWareList.map(item => ({
          hardware_id: item.hardware_id,
          model: item.model,
          category: item.category,
          install_date: new Date(item.install_date * 1000).toLocaleDateString(),
          warranty_end_date: new Date(item.warranty_end_date * 1000).toLocaleDateString(),
          ip_address: item.ip_address,
          cpu_type: item.cpu_type,
          member_cache: item.member_cache,
          disk_space: item.disk_space,
          network_type: item.network_type,
          gpu_type: item.gpu_type
        }))
        total.value = response.data.HardWareList.length // 设置总记录数
      } else {
        ElMessage.error(response.msg)
      }
    } else {
      ElMessage.error('未找到 NodeId')
    }
  } catch (error) {
    ElMessage.error('获取硬件数据失败')
  }
}

onMounted(() => {
  getTableData()
})
</script>

<style scoped>
.gva-search-box {
  margin-bottom: 20px;
}

.gva-table-box {
  margin-bottom: 20px;
}

.gva-btn-list {
  margin-bottom: 10px;
}

.gva-pagination {
  margin-top: 20px;
}

.info p {
  padding: 5px 0; /* 设置上下内边距 */
  margin: 0; /* 可以设置外边距为0或根据需要调整 */
}
</style>


